package com.ymatou.query.seller.trading.api.testcase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.query.seller.trading.api.parameter.GetOrderProductAmountInfosBean;
import com.ymatou.query.seller.trading.api.parameter.GetOrderProductAmountInfosResponse;
import com.ymatou.query.seller.trading.api.service.GetOrderProductAmountInfosCall;
import com.ymatou.query.seller.trading.api.service.OrderCreate;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;

/**
 * @date 2016-09-06
 * @author songyefeng
 * @desc 根据商品Id获取订单中商品数量信息
 */
@TestSuite
public class Ts_GetOrderProductAmountInfos {

	private static GetOrderProductAmountInfosBean getOrderProductAmountInfosBean;
	private static GetOrderProductAmountInfosCall getOrderProductAmountInfosCall;

	// private static GetOrderProductAmountInfosCall_java
	// getOrderProductAmountInfosCall;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("根据商品Id获取订单中商品数量信息");
	}

	@Before
	public void caseUp() {
		getOrderProductAmountInfosBean = new GetOrderProductAmountInfosBean();
		getOrderProductAmountInfosCall = new GetOrderProductAmountInfosCall();
		// getOrderProductAmountInfosCall = new
		// GetOrderProductAmountInfosCall_java();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(getOrderProductAmountInfosCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private void verify() {
		GetOrderProductAmountInfosResponse expectedResponse = new GetOrderProductAmountInfosResponse();
		ConstructExpectedResponse(expectedResponse);
		GetOrderProductAmountInfosResponse actualResponse = getOrderProductAmountInfosCall
				.getOrderProductAmountInfosResponse();
		DataUtil.verifyEquals(expectedResponse.getAmountInfos().size(),
				actualResponse.getAmountInfos().size(), "验证AmountInfos的数量");
		Iterator<String> it = actualResponse.getAmountInfos().keySet()
				.iterator();
		while (it.hasNext()) {
			String actPid = it.next();
			GetOrderProductAmountInfosResponse.OrderProductAmountInfo actual = actualResponse
					.getAmountInfos().get(actPid);
			boolean exists = expectedResponse.getAmountInfos().containsKey(
					actPid);
			DataUtil.verifyEquals(true, exists, "验证ProductId: " + actPid
					+ "是否应该出现在返回结果中");
			if (exists) {
				GetOrderProductAmountInfosResponse.OrderProductAmountInfo expect = expectedResponse
						.getAmountInfos().get(actPid);
				DataUtil.verifyEquals(expect.getPaid(), actual.getPaid(),
						"验证ProductId: " + actPid + "的Paid值");
				DataUtil.verifyEquals(expect.getUnpaid(), actual.getUnpaid(),
						"验证ProductId: " + actPid + "的Unpaid值");
			}
		}
	}

	@SuppressWarnings("rawtypes")
	private void ConstructExpectedResponse(
			GetOrderProductAmountInfosResponse response) {
		List<String> productIds = getOrderProductAmountInfosBean
				.getProductIds().stream().distinct()
				.collect(Collectors.toList());
		List<Map> results = execute(productIds);
		ConvertResult(response, results);

	}

	@SuppressWarnings("rawtypes")
	private void ConvertResult(GetOrderProductAmountInfosResponse response,
			List<Map> results) {
		Map<String, GetOrderProductAmountInfosResponse.OrderProductAmountInfo> AmountInfos = new HashMap<String, GetOrderProductAmountInfosResponse.OrderProductAmountInfo>();
		if (DataUtil.isNullOrEmpty(getOrderProductAmountInfosBean
				.getProductIds()) == false) {
			for (int i = 0; i < getOrderProductAmountInfosBean.getProductIds()
					.size(); i++) {
				String pid = getOrderProductAmountInfosBean.getProductIds()
						.get(i);
				GetOrderProductAmountInfosResponse.OrderProductAmountInfo o = new GetOrderProductAmountInfosResponse.OrderProductAmountInfo();
				o.setProductId(pid);
				boolean has = results.stream().anyMatch(
						x -> x.get("ProductId").equals(pid));
				if (has == false) {
					o.setPaid(0);
					o.setUnpaid(0);
				} else {
					Map match = results.stream()
							.filter(x -> x.get("ProductId").equals(pid))
							.collect(Collectors.toList()).get(0);
					o.setPaid(DataUtil.Integerr.GetValueOrDefault(match
							.get("Paid")));
					o.setUnpaid(DataUtil.Integerr.GetValueOrDefault(match
							.get("Unpaid")));
				}
				AmountInfos.put(o.getProductId(), o);
			}
		}
		response.setAmountInfos(AmountInfos);
	}

	@SuppressWarnings("rawtypes")
	private List<Map> execute(List<String> productIds) {
		DefaultWapper defaultWapper = new DefaultWapper();
		String queryField = " oi.sproductId as ProductId";
		queryField += " , sum(IIF(o.itradingstatus = 1, oi.iAmount, 0)) as Unpaid";
		queryField += " , sum(IIF(o.itradingstatus in (2,3,4,16,17), oi.iAmount, 0)) as Paid";
		String joinCondition = " join ymt_orders(nolock) o on oi.iorderid = o.iorderid ";
		StringBuffer queryCondition = new StringBuffer();
		if (DataUtil.isNullOrEmpty(productIds) == false) {
			queryCondition.append(" oi.sproductId in "
					+ DataUtil.toInOfSql(productIds));
		}
		queryCondition.append(" group by oi.sproductId");
		return defaultWapper.selectOrderInfo(queryField, joinCondition,
				queryCondition.toString());
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_001() {
		Logger.start(true, "根据商品Id获取订单中商品数量信息");
		try {
			List<String> productIds = new ArrayList<String>();
			Logger.comment("准备前置数据");
			OrderCreate c = new OrderCreate();
			int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			productIds
					.add(c.create1_M2cOrder(userId, sellerId).getsProductId());
			productIds
					.add(c.create2_PayOrder(userId, sellerId).getsProductId());
			productIds.add(c.create3_ShippedOrder(userId, sellerId)
					.getsProductId());
			productIds.add(c.create4_ReceivedOrder(userId, sellerId)
					.getsProductId());
			productIds.add(c.create4_ApplyRefundOrder(userId, sellerId)
					.getsProductId());
			productIds.add(c.create4_RefundOrder(userId, sellerId)
					.getsProductId());
			Logger.comment("准备前置数据结束");
			getOrderProductAmountInfosBean.setProductIds(productIds);
			getOrderProductAmountInfosCall
					.setData(getOrderProductAmountInfosBean);
			getOrderProductAmountInfosCall.callService();
			Logger.comment("getOrderProductAmountInfosCall send:"
					+ getOrderProductAmountInfosCall.getEntityString());
			Logger.comment("getOrderProductAmountInfosCall response:"
					+ getOrderProductAmountInfosCall.getReturnData());
			Logger.verifyEquals("200",
					getOrderProductAmountInfosCall.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_002() {
		Logger.start(true, "根据商品Id获取订单中商品数量信息,productIds为空");
		try {
			List<String> productIds = new ArrayList<String>();
			getOrderProductAmountInfosBean.setProductIds(productIds);
			getOrderProductAmountInfosCall
					.setData(getOrderProductAmountInfosBean);
			getOrderProductAmountInfosCall.callService();
			Logger.comment("getOrderProductAmountInfosCall send:"
					+ getOrderProductAmountInfosCall.getEntityString());
			Logger.comment("getOrderProductAmountInfosCall response:"
					+ getOrderProductAmountInfosCall.getReturnData());
			DataUtil.verifyEquals(400,
					getOrderProductAmountInfosCall.getCode(), "验证code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_GetOrderProductAmountInfos_003() {
		Logger.start(true, "根据商品Id获取订单中商品数量信息,productId不存在");
		try {
			List<String> productIds = new ArrayList<String>();
			productIds.add("meiyougaiproductid");
			getOrderProductAmountInfosBean.setProductIds(productIds);
			getOrderProductAmountInfosCall
					.setData(getOrderProductAmountInfosBean);
			getOrderProductAmountInfosCall.callService();
			Logger.comment("getOrderProductAmountInfosCall send:"
					+ getOrderProductAmountInfosCall.getEntityString());
			Logger.comment("getOrderProductAmountInfosCall response:"
					+ getOrderProductAmountInfosCall.getReturnData());
			DataUtil.verifyEquals(200,
					getOrderProductAmountInfosCall.getCode(), "验证code");
			verify();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

}